/*
 * Copyright 2010 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.persistence;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.shalma.Service;
import org.shalma.internal.EntityRegistry;
import org.shalma.model.Id;
import org.shalma.model.Property;
import org.shalma.persistence.Translator;

public class TranslatorManager implements Service {

	private final Map<Class<?>, Translator<?, ?>> classTotranslators;
	private final Map<String, Translator<?, ?>> idToTranslators;

	@SuppressWarnings("unchecked")
	private TranslatorManager() {

		classTotranslators = new HashMap<Class<?>, Translator<?, ?>>();
		idToTranslators = new HashMap<String, Translator<?, ?>>();

		nullTranslators(String.class, Long.class, Double.class, Boolean.class);
		addTranslator(ArrayList.class, new ListTranslator());

		for (Class<? extends Property<?>> propertyClass : EntityRegistry.instance
				.getProperties())
			addTranslator(propertyClass, new PropertyTranslator(propertyClass));

	}

	public void addTranslator(Class<?> type, Translator<?, ?> translator) {

		classTotranslators.put(type, translator);
		idToTranslators.put(translator.getTypeId(), translator);
	}

	public Translator<?, ?> getTranslator(Class<?> type) {
		return classTotranslators.get(type);
	}

	public Translator<?, ?> getTranslator(String typeId) {
		return idToTranslators.get(typeId);
	}

	void nullTranslators(Class<?>... types) {

		Translator nullTranslator = new NullTranslator();
		for (Class<?> type : types) {
			classTotranslators.put(type, nullTranslator);
		}
		idToTranslators.put(nullTranslator.getTypeId(), nullTranslator);
	}
}
